package com.thirdgroup.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thirdgroup.controller.base.BaseServlet;
import com.thirdgroup.service.PhoneBillService;
import com.thirdgroup.service.impl.PhoneBillServiceImpl;
import com.thirdgroup.utils.respond.R;
import org.junit.Test;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@WebServlet("/phonebill/*")
public class PhoneBillServlet extends BaseServlet {
    private PhoneBillService phoneBillService=new PhoneBillServiceImpl();
    public void selectByUserPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 从请求体中获取 JSON 字符串
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();

        // 使用 ObjectMapper 将 JSON 字符串转换为 Map 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data = objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});

        // 获取ID
        String userPhone = data.get("userPhone");
        System.out.println("根据电话卡查账单信息");
        System.out.println("userPhone=="+userPhone);

        R r = phoneBillService.selectUserPhone(userPhone);
        System.out.println("根据电话卡查找到数据如下：");
        System.out.println(r.getData());
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
